import {Component, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {ModalDirective} from 'ngx-bootstrap';
import {TagList, TagInfo, AddTag, EditTag, AddActivity, EditActivity} from './tag';
import {CouponsService} from '../../lib/service/admin/coupons.service';
import {BannerService} from "./banner.service";
import {AdOssUploadService} from "../../lib/service/ad-oss-upload.service";
import {NzMessageService} from "ng-zorro-antd";
import {AliyunOssOutputUrl} from "../../../config/api";
import {CategoryService} from "../category/category.service";
import {LoginService} from "../../lib/service/tuike-login.service";

@Component({
  selector: 'app-banner',
  templateUrl: './banner.component.html',
  styleUrls: ['./banner.component.scss'],
  providers: [CouponsService, BannerService, CategoryService]
})
export class BannerComponent implements OnInit {

  totalItems: number;
  currentPage = 1;
  itemsPerPage = 10;
  name: string;
  model: string;
  orderField: string;
  orderSort: string;
  type: string;
  message: string;
  isShow = false;
  addActivity = new AddActivity();
  editActivity = new EditActivity();


  fileList = [];
  picList = [];
  fileList1 = [];
  picList1 = [];
  taskList = [];
  typeList = [];

  task_ids = [];
  checkedTaskInfo = [];
  taskModalVisible = false;
  taskPage = 1;
  taskPageSize = 5;
  taskTotal = 0;
  isConfirmTaskLoading = false;
  taskLoading = false;
  activityList = [];
  submitStatus = false;
  confirmStatus = null;
  confirmId = null;
  confirmTitle = '';
  _isSpinning = false;
  categories = [];
  canVisit = false;
  canVisit1 = false;
  canVisit2 = false;
  canVisit3 = false;

  @ViewChild('addModal') public addModal: ModalDirective;
  @ViewChild('editModal') public editModal: ModalDirective;
  @ViewChild('confirmModal') public confirmModal: ModalDirective;

  constructor(
    private router: Router,
    private couponsService: CouponsService,
    private bannerService: BannerService,
    private adOssUploadService: AdOssUploadService,
    private _message: NzMessageService,
    private categoryService: CategoryService,
    private route:ActivatedRoute,
    private loginService: LoginService
  ) {
    this.name = '';
    this.model = '';
    this.orderField = '';
    this.orderSort = '';
  }

  ngOnInit() {
    this.route.snapshot.queryParams['page'] ? this.currentPage = +this.route.snapshot.queryParams['page']: this.currentPage = 1;
    this.categoryService.getCategoryList(1, 0).subscribe(res => {
      if (res.code === 200) {
        this.categories = res.data;
        this.getActivityList();
      }
    });
    this.canVisit = this.loginService.canVisitCheck('activity_add');
    this.canVisit1 = this.loginService.canVisitCheck('activity_edit');
    this.canVisit2 = this.loginService.canVisitCheck('activity_delete');
    this.canVisit3 = this.loginService.canVisitCheck('activity_change_status');
  }

  picError = false;
  picError1 = false;

  fileChange() {
    if (this.fileList.length == 0 && this.picList.length == 0) {
      this.picError = true;
    } else {
      this.picError = false;
    }
  }

  fileChange1() {
    if (this.fileList1.length == 0 && this.picList1.length == 0) {
      this.picError1 = true;
    } else {
      this.picError1 = false;
    }
  }

  showAddModal() {
    this.addModal.show();
  }

  showEditModal() {
    this.editModal.show();
  }
  addTask(e) {
    this.taskModalVisible = true;
  }

  getTaskList() {
    this.bannerService.getTaskList(this.taskPage, this.taskPageSize).subscribe(res => {
      if (res.code === 200) {
        let data = res.data;
        this.taskList = data.list.data;
        this.taskTotal = data.list.total;
        let task_type = data.task_type;
        for (let key in  task_type) {
          this.typeList.push({
            'label': task_type[key],
            'value': key
          })
        }
        ;
        this.taskList.map((e, i) => {
          e['taskPreview'] = `${AliyunOssOutputUrl}/${e['task_content']['image']}?update=${new Date().getTime()}`;
          e['checked'] = false;
          if (this.checkedTaskInfo.length > 0) {
            this.checkedTaskInfo.map((e1, i1) => {
              if (e.id == e1.id) {
                e['checked'] = true;
              }
            })
          }
        });
      }
    })
  }


  // getActivityInfo(id) {
  //   this.bannerService.getActivityInfo(id).subscribe(res => {
  //     if (res.code == 200) {
  //       let data = res.data;
  //       this.addActivity.activity_name = data.activity_name;
  //       this.addActivity.type = data.type;
  //       this.addActivity.sort = data.sort;
  //       this.addActivity.comment = data.comment;
  //       this.addActivity.first_category_id = data.first_category_id;
  //       let task_ids = JSON.parse(data.task_ids);
  //       this.checkedTaskInfo = [];
  //       this.bannerService.getTaskList(1, 666).subscribe(res => {
  //         if (res.code == 200) {
  //           let taskList = res.data.list.data;
  //           taskList.map((e, i) => {
  //             e['taskPreview'] = `${AliyunOssOutputUrl}/${e['task_content']['image']}?update=${new Date().getTime()}`;
  //             task_ids.map((e1, i1) => {
  //               if (e.id == e1) {
  //                 this.task_ids.push(e);
  //               }
  //             })
  //           });
  //           this.checkedTaskInfo = this.task_ids;
  //         }
  //       });
  //       if (data.pic) {
  //         this.picList.push({src: `${AliyunOssOutputUrl}/${data.pic}?update=${new Date().getTime()}`});
  //         this.fileList.push('pic');
  //         this.canChange = true;
  //       }
  //     }
  //   })
  // }


  getActivityList() {
    this._isSpinning = true;
    this.bannerService.getActivityList(this.currentPage, this.itemsPerPage).subscribe(res => {
      if (res.code == 200) {
        this._isSpinning = false;
        this.activityList = res.data.data;
        this.totalItems = res.data.total;
        this.activityList.map((e, i) => {
          if (e.pic) {
            e.pic = `${AliyunOssOutputUrl}/${e.pic}?update=${new Date().getTime()}`
          }
          if (this.categories.length > 0) {
            this.categories.forEach((e1, i1) => {
              if (e1.id == e.first_category_id) {
                e['category_name'] = e1['category_name'];
              }
            });
          }
        })
      }
    })
  }

  showConfirmModal(id, title, status) {
    this.confirmModal.show();
    this.confirmStatus = status;
    this.confirmId = id;
    this.confirmTitle = title;
  }


  closeConfirmModal() {
    this.confirmModal.hide();
  }

  changeStatus() {
    this.bannerService.changeStatus({'status': this.confirmStatus, 'id': this.confirmId}).subscribe(res => {
      if (res.code === 200) {
        this.confirmModal.hide();
        this.type = 'success';
        this.message = '修改状态成功!';
        this.isShow = true;
        setTimeout(() => {
          this.getActivityList();
        }, 300);
      }
    })
  }

  closeTaskModal() {
    this.taskModalVisible = false;
  }

  goActivity() {
    // this.taskModalVisible = true;
    this.router.navigate(['tuike/activity/add']);
  }


  dealTask(e, data) {
    this.taskList.map((item, i) => {
      if (item.id == data.id) {
        if (this.task_ids.length == 0) {
          if (e) {
            item['checked'] = true;
            this.task_ids.push(data);
          }
        } else {
          if (e) {
            let num = 0;
            this.task_ids.map((item1, i) => {
              if (item1.id != data.id && num === 0) {
                item['checked'] = true;
                this.task_ids.push(data);
                num++;
              }
              return;
            });
          } else {
            this.task_ids.map((item2, i) => {
              if (item2.id == data.id) {
                item['checked'] = false;
                this.task_ids.splice(i, 1);
                return;
              }
              return;
            });
          }
        }
      }
    });
    this.checkedTaskInfo = this.task_ids;
  }

  delete() {
    this.bannerService.deleteActivity({id: this.confirmId}).subscribe(res => {
      if (res.code == 200) {
        this.confirmModal.hide();
        this.type = 'success';
        this.message = '删除成功';
        this.isShow = true;
        this.currentPage = 1;
        setTimeout(() => {
          this.getActivityList();
        }, 300);
      }
    })
  }

  uploadImg(activity_id) {
    this.adOssUploadService
      .getSignature('/v1/admin/tuike_activity/' + activity_id + '?callback=true')
      .subscribe(
        res1 => {
          let length = this.fileList.filter(item => {
            return item && item != "pic";
          }).length;
          let successLen = 0;
          if (length == 0) {
            // this.submitStatus = false;
            this._message.create("success", '添加成功');
            return false;
          }
          this.fileList.every((val, idx, array) => {
            if (val && val != "pic") {
              this.adOssUploadService.fileUpload(val, res1.data, 'tuike_activity_pic' + '.' + val.name.replace(/.+\./, '').toLowerCase(), 'image')
                .subscribe(res2 => {
                    successLen++;
                    if (successLen == length) {
                      this.submitStatus = false;
                      this._message.create('success', '添加成功');
                      this.addModal.hide();
                      this.currentPage = 1;
                      this.getActivityList();
                    }
                  }
                );
            }
            return true;
          });
        }
      );
  }

  addActivityFormSubmit(e) {
    e.stopPropagation();
    if (this.checkedTaskInfo.length == 0) {
      this.isShow = false;
      this.message = '请添加任务';
      this.type = 'error';
      return;
    }
    let data = Object.assign(this.addActivity);
    data['task_ids'] = [];
    this.checkedTaskInfo.map((e, i) => {
      data['task_ids'].push(e.id);
    });
    this.submitStatus = true;
    this.bannerService.addActivity(data).subscribe(res => {
      if (res.code == 200) {
        let id = res.data.id;
        this.uploadImg(id);
      }
    })
  }


  goEdit(id) {
    this.router.navigate(['tuike/activity/add'], {
      queryParams: {
        id: id,
        page:this.currentPage
      }
    });
  }


  editActivityFormSubmit(e) {
    e.stopPropagation();
    if (this.checkedTaskInfo.length == 0) {
      this.isShow = false;
      this.message = '请添加任务';
      this.type = 'error';
      return;
    }
    let data = Object.assign(this.addActivity);
    data['task_ids'] = [];
    this.checkedTaskInfo.map((e, i) => {
      data['task_ids'].push(e.id);
    });
  }

  pageChanged(event: any): void {
    window.scrollTo(0, 0);
    this.currentPage = event.page;
    this.getActivityList();
  }

  promptIsShow(event: any): void {
    this.isShow = event;
  }
}
